const app = new Vue({
    el: '#app',
    data() {
        return {
            form: {
                name: "",
                pwd: "",
                client: getUrlParams(location.href)["client"]
            },
            rules: {
                name: [
                    {required: true, message: '请输入用户名', trigger: 'blur'},
                    {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
                ],
                pwd: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                    {min: 5, max: 50, message: '长度在 5 到 50 个字符', trigger: 'blur'}
                ],
            }
        }
    },
    mounted() {
        window.addEventListener('keydown', function (event) {
            if (event.key === 'Enter' || event.keyCode === 13) {
                app.onSubmit();
            }
        });
    },
    methods: {
        onSubmit() {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    const {name, pwd, client} = this.form;

                    const loading = this.$loading({
                        lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'
                    });

                    Vue.http.options.emulateJSON = true
                    this.$http.post("/sso/doLogin", {name, pwd, client}).then(function (res) {
                        let body = res.body;
                        let status;
                        if (body.code === 200) {
                            status = "success";
                            setTimeout(function () {
                                location.reload();
                            }, 1000);
                        } else {
                            status = "error";
                        }

                        this.$message({
                            message: body.msg, type: status
                        });
                    }).finally(() => {
                        loading.close();
                    });
                }
            });
        }
    }
});

function getUrlParams(url) {
    const urlObj = new URL(url);
    const params = {};
    for (const [key, value] of urlObj.searchParams.entries()) {
        params[key] = value;
    }
    return params;
}
